package com.app.couponsharelife.ui.main

import android.content.Intent
import android.view.MotionEvent
import android.view.View
import android.view.animation.Interpolator
import android.widget.Scroller
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.ui.adapter.WelcomeIndicatorAdapter
import com.app.couponsharelife.ui.adapter.WelcomeViewAdapter
import com.app.couponsharelife.ui.main.login.NewLoginActivity
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_welcome.*
import java.util.concurrent.TimeUnit


class WelcomeActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_welcome

    private var disposable: Disposable? = null

    private var mWindowWidth = 0

    private var mWindowHeight = 0

    private var isTouchIng = false

    private var selectPageTime = 0L

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        mWindowWidth = AppUtils.getDisplayMetrics(this).widthPixels
        mWindowHeight = AppUtils.getDisplayMetrics(this).heightPixels
        initViewPagerScroll()
        initViewPager()
        tvGoMain.setOnClickListener {
            AppUtils.setString("is_first", "1")
            startActivity(Intent(this, NewLoginActivity::class.java))
            finish()
        }
    }

    private fun initViewPager() {
        mViewPager.adapter = WelcomeViewAdapter(this, arrayListOf(1, 1, 1))
        mViewPager.offscreenPageLimit = 3
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                /*if (!isFirst) {
                    if (position == 0) {
                        ivWelcomePic1.alpha = 1 - positionOffset
                        ivWelcomePic2.alpha = positionOffset
                        val layoutParams1 = ConstraintLayout.LayoutParams(0, 0)
                        layoutParams1.matchConstraintPercentWidth = (0.636 * (1 - positionOffset)).toFloat()
                        layoutParams1.topToTop = R.id.mRootContainer
                        layoutParams1.endToEnd = R.id.mRootContainer
                        layoutParams1.topMargin = (mWindowHeight * 0.067 + positionOffset * (mWindowHeight / 8)).toInt()
                        layoutParams1.marginEnd = (mWindowWidth * 0.144 * (1 - positionOffset)).toInt()
                        layoutParams1.dimensionRatio = "1:0.65"
                        ivWelcomePic1.layoutParams = layoutParams1

                        val layoutParams2 = ConstraintLayout.LayoutParams(0, 0)
                        layoutParams2.matchConstraintPercentWidth = (0.747 * positionOffset).toFloat()
                        layoutParams2.topToTop = R.id.mRootContainer
                        layoutParams2.startToStart = R.id.mRootContainer
                        layoutParams2.topMargin = (mWindowHeight * 0.09 + (1 - positionOffset) * (mWindowHeight / 8)).toInt()
                        layoutParams2.marginStart = (mWindowWidth * 0.04 * positionOffset).toInt()
                        layoutParams2.dimensionRatio = "1:0.84"
                        ivWelcomePic2.layoutParams = layoutParams2
                    } else if (position == 1) {
                        ivWelcomePic2.alpha = 1 - positionOffset
                        ivWelcomePic3.alpha = positionOffset

                        val layoutParams1 = ConstraintLayout.LayoutParams(0, 0)
                        layoutParams1.matchConstraintPercentWidth = (0.747 * (1 - positionOffset)).toFloat()
                        layoutParams1.topToTop = R.id.mRootContainer
                        layoutParams1.endToEnd = R.id.mRootContainer
                        layoutParams1.topMargin = (mWindowHeight * 0.09 + positionOffset * (mWindowHeight / 8)).toInt()
                        layoutParams1.marginEnd = (mWindowWidth * 0.213 * (1 - positionOffset)).toInt()
                        layoutParams1.dimensionRatio = "1:0.84"
                        ivWelcomePic2.layoutParams = layoutParams1

                        val layoutParams2 = ConstraintLayout.LayoutParams(0, 0)
                        layoutParams2.matchConstraintPercentWidth = (0.71 * positionOffset).toFloat()
                        layoutParams2.topToTop = R.id.mRootContainer
                        layoutParams2.startToStart = R.id.mRootContainer
                        layoutParams2.topMargin = (mWindowHeight * 0.08 + (1 - positionOffset) * (mWindowHeight / 8)).toInt()
                        layoutParams2.marginStart = (mWindowWidth * 0.155 * positionOffset).toInt()
                        layoutParams2.dimensionRatio = "1:0.48"
                        ivWelcomePic3.layoutParams = layoutParams2
                    }
                } else {
                    isFirst = false
                }*/
            }

            override fun onPageSelected(position: Int) {
                selectPageTime = System.currentTimeMillis()
                (mRecyclerView.adapter as WelcomeIndicatorAdapter).pos = position
                (mRecyclerView.adapter as WelcomeIndicatorAdapter).notifyDataSetChanged()
                tvGoMain.visibility = if (position == 2) View.VISIBLE else View.INVISIBLE
                mRecyclerView.visibility = if (position == 2) View.INVISIBLE else View.VISIBLE
            }
        })
        mViewPager.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    isTouchIng = true
                }
                MotionEvent.ACTION_UP -> {
                    isTouchIng = false
                }
            }
            super.onTouchEvent(event)
        }
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        mRecyclerView.layoutManager = layoutManager
        mRecyclerView.adapter = WelcomeIndicatorAdapter(0, arrayListOf(1, 1, 1))
        mViewPager.post {
            AppUtils.setViewPagerScroller(this, mViewPager)
        }

        countDown()
    }

    private fun countDown() {
        if (disposable == null) {
            disposable = Observable.interval(0, 3, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ aLong ->
                        if (aLong != 0L) {
                            resumeAnimation()
                        }
                    }, {
                        resumeAnimation()
                    })
        }
    }

    private fun resumeAnimation() {
        if (isTouchIng || (System.currentTimeMillis() - selectPageTime) < 2000) return
        val currentItem = mViewPager.currentItem + 1
        if (currentItem < mViewPager.adapter!!.count)
            mViewPager.currentItem = currentItem
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
        disposable?.dispose()
        disposable = null
    }

    private fun initViewPagerScroll() {
        try {
            val scrollerField = ViewPager::class.java.getDeclaredField("mScroller")
            scrollerField.isAccessible = true
            val interpolator = ViewPager::class.java.getDeclaredField("sInterpolator")
            interpolator.isAccessible = true

            val scroller = object : Scroller(this, interpolator.get(null) as Interpolator) {
                override fun startScroll(startX: Int, startY: Int, dx: Int, dy: Int, duration: Int) {
                    super.startScroll(startX, startY, dx, dy, 1000)
                }

                override fun startScroll(startX: Int, startY: Int, dx: Int, dy: Int) {
                    super.startScroll(startX, startY, dx, dy, 1000)
                }
            }
            scrollerField.set(mViewPager, scroller)
        } catch (e: NoSuchFieldException) {
            // Do nothing.
        } catch (e: IllegalAccessException) {
            // Do nothing.
        }
    }
}